<template>
  <view class="vehicle-detail-page page-content">
    <up-navbar title="车辆详情" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder @leftClick="handleBackToDetail" />
    
    <view class="detail-container">
      <!-- 车辆基本信息 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">车辆信息</text>
          <view class="status-badge" :class="getStatusClass(vehicleDetail.status)">
            {{ getStatusText(vehicleDetail.status) }}
          </view>
        </view>
        
        <view class="card-content">
          <view class="vehicle-plate-section">
            <text class="plate-number">{{ vehicleDetail.plateNumber }}</text>
            <view class="vehicle-type">{{ getVehicleTypeText(vehicleDetail.vehicleType) }}</view>
          </view>
          
          <view class="info-grid">
            <view class="info-item">
              <text class="info-label">车主姓名</text>
              <text class="info-value">{{ vehicleDetail.ownerName }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">联系电话</text>
              <text class="info-value">{{ vehicleDetail.phone }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">泊位编号</text>
              <text class="info-value">{{ vehicleDetail.parkingSpace }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">车辆颜色</text>
              <text class="info-value">{{ vehicleDetail.vehicleColor }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">车辆品牌</text>
              <text class="info-value">{{ vehicleDetail.vehicleBrand }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">登记时间</text>
              <text class="info-value">{{ vehicleDetail.registerTime }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 核验记录 -->
      <view class="verify-card">
        <view class="card-header">
          <text class="card-title">核验记录</text>
        </view>
        
        <view class="card-content">
          <view class="verify-info" v-if="vehicleDetail.verifyTime">
            <view class="verify-item">
              <text class="verify-label">核验时间：</text>
              <text class="verify-value">{{ vehicleDetail.verifyTime }}</text>
            </view>
            <view class="verify-item">
              <text class="verify-label">核验人员：</text>
              <text class="verify-value">{{ vehicleDetail.verifyPerson }}</text>
            </view>
            <view class="verify-item">
              <text class="verify-label">核验结果：</text>
              <text class="verify-value" :class="getResultClass(vehicleDetail.result)">{{ vehicleDetail.result }}</text>
            </view>
            <view class="verify-item" v-if="vehicleDetail.verifyRemark">
              <text class="verify-label">备注说明：</text>
              <text class="verify-value">{{ vehicleDetail.verifyRemark }}</text>
            </view>
          </view>
          
          <view class="no-verify" v-else>
            <text class="no-verify-text">暂未进行核验</text>
          </view>
        </view>
      </view>
      
      <!-- 现场照片 -->
      <view class="photo-card" v-if="vehicleDetail.photos && vehicleDetail.photos.length > 0">
        <view class="card-header">
          <text class="card-title">现场照片</text>
        </view>
        
        <view class="card-content">
          <view class="photo-grid">
            <view class="photo-item" v-for="(photo, index) in vehicleDetail.photos" :key="index"
              @click="previewPhoto(index)">
              <image class="photo-image" :src="photo.url" mode="aspectFill" />
              <text class="photo-desc">{{ photo.description }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 历史记录 -->
      <view class="history-card" v-if="vehicleDetail.historyRecords && vehicleDetail.historyRecords.length > 0">
        <view class="card-header">
          <text class="card-title">历史记录</text>
        </view>
        
        <view class="card-content">
          <view class="history-list">
            <view class="history-item" v-for="(record, index) in vehicleDetail.historyRecords" :key="index">
              <view class="history-time">
                <text class="time-text">{{ record.time }}</text>
              </view>
              <view class="history-content">
                <text class="action-text">{{ record.action }}</text>
                <text class="operator-text">操作人：{{ record.operator }}</text>
                <text class="remark-text" v-if="record.remark">{{ record.remark }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-card" v-if="vehicleDetail.status === 'pending' || vehicleDetail.status === 'unconfirmed'">
        <view class="action-buttons">
          <up-button 
            type="success"
            :text="vehicleDetail.status === 'unconfirmed' ? '确认处理' : '核验通过'"
            @click="handleApprove"
            :customStyle="{
              flex: 1,
              marginRight: '20rpx',
              height: '80rpx'
            }"
          />
          <up-button 
            type="default"
            :text="vehicleDetail.status === 'unconfirmed' ? '拒绝处理' : '核验驳回'"
            @click="handleReject"
            :customStyle="{
              flex: 1,
              height: '80rpx',
              color: '#f5222d',
              backgroundColor: '#fff',
              border: '1px solid #f5222d'
            }"
          />
        </view>
      </view>
    </view>
    
    <!-- 驳回原因弹窗 -->
    <up-popup v-model:show="showRejectModal" mode="center" round="20">
      <view class="reject-modal">
        <view class="modal-header">
          <text class="modal-title">驳回原因</text>
        </view>
        
        <view class="modal-content">
          <up-textarea 
            v-model="rejectReason"
            placeholder="请输入驳回原因"
            :maxlength="200"
            count
            :customStyle="{
              backgroundColor: '#f5f5f5',
              borderRadius: '12rpx'
            }"
          />
        </view>
        
        <view class="modal-footer">
          <up-button 
            text="取消"
            type="info"
            plain
            @click="showRejectModal = false"
            :customStyle="{
              flex: 1,
              marginRight: '20rpx',
              height: '80rpx'
            }"
          />
          <up-button 
            text="确定"
            type="error"
            @click="confirmReject"
            :customStyle="{
              flex: 1,
              height: '80rpx'
            }"
          />
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const taskId = ref('')
const vehicleId = ref('')
const showRejectModal = ref(false)
const rejectReason = ref('')

// 车辆详情数据
const vehicleDetail = reactive({
  id: '',
  plateNumber: '',
  ownerName: '',
  phone: '',
  vehicleType: '',
  vehicleColor: '',
  vehicleBrand: '',
  parkingSpace: '',
  registerTime: '',
  status: 'pending',
  verifyTime: '',
  verifyPerson: '',
  result: '',
  verifyRemark: '',
  photos: [],
  historyRecords: []
})

// 页面加载
onLoad((options) => {
  taskId.value = options.taskId || ''
  vehicleId.value = options.vehicleId || options.id || ''
  const type = options.type || ''
  
  // 根据类型加载不同的数据
  if (type === 'unconfirmed') {
    loadUnconfirmedOrderDetail()
  } else {
    loadVehicleDetail()
  }
})

// 加载车辆详情
const loadVehicleDetail = async () => {
  try {
    // TODO: 调用API获取车辆详情
    // const res = await getVehicleDetail(vehicleId.value)
    
    // 模拟数据
    Object.assign(vehicleDetail, {
      id: vehicleId.value,
      plateNumber: '京A12345',
      ownerName: '张三',
      phone: '138****1234',
      vehicleType: 'car',
      vehicleColor: '白色',
      vehicleBrand: '大众',
      parkingSpace: 'A-001',
      registerTime: '2023-12-01 10:00:00',
      status: 'pending',
      verifyTime: '',
      verifyPerson: '',
      result: '',
      verifyRemark: '',
      photos: [
        {
          url: 'https://via.placeholder.com/300x200',
          description: '车辆正面照'
        },
        {
          url: 'https://via.placeholder.com/300x200',
          description: '车牌照片'
        },
        {
          url: 'https://via.placeholder.com/300x200',
          description: '泊位照片'
        }
      ],
      historyRecords: [
        {
          time: '2024-01-10 09:00:00',
          action: '车辆登记',
          operator: '系统管理员',
          remark: '车辆信息录入系统'
        },
        {
          time: '2024-01-15 08:30:00',
          action: '分配核验任务',
          operator: '张三',
          remark: '分配给核验人员进行现场核验'
        }
      ]
    })
  } catch (error) {
    console.error('加载车辆详情失败:', error)
  }
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const statusMap = {
    'pending': 'status-pending',
    'completed': 'status-completed',
    'unconfirmed': 'status-unconfirmed'
  }
  return statusMap[status] || 'status-pending'
}

// 加载未确认订单详情
const loadUnconfirmedOrderDetail = async () => {
  try {
    // TODO: 调用API获取未确认订单详情
    // const res = await getUnconfirmedOrderDetail(vehicleId.value)
    
    // 模拟数据
    Object.assign(vehicleDetail, {
      id: vehicleId.value,
      plateNumber: '粤B12345',
      ownerName: '李四',
      phone: '139****5678',
      vehicleType: 'car',
      vehicleColor: '黑色',
      vehicleBrand: '本田',
      parkingSpace: 'B-123',
      registerTime: '2023-11-15 14:30:00',
      status: 'unconfirmed',
      verifyTime: '2024-01-15 10:30:00',
      verifyPerson: '张三',
      result: '未确认',
      verifyRemark: '车辆信息与登记不符',
      photos: [
        {
          url: 'https://via.placeholder.com/300x200',
          description: '车辆现场照片'
        },
        {
          url: 'https://via.placeholder.com/300x200',
          description: '车牌照片'
        }
      ],
      historyRecords: [
        {
          time: '2023-11-15 14:30:00',
          action: '车辆登记',
          operator: '系统管理员',
          remark: '车辆信息录入系统'
        },
        {
          time: '2024-01-15 10:30:00',
          action: '现场核验',
          operator: '张三',
          remark: '车辆信息与登记不符，标记为未确认'
        }
      ]
    })
  } catch (error) {
    console.error('加载未确认订单详情失败:', error)
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    'pending': '待处理',
    'completed': '已完成',
    'unconfirmed': '未确认'
  }
  return statusMap[status] || '未知'
}

// 获取车辆类型文本
const getVehicleTypeText = (type: string) => {
  const typeMap = {
    'car': '小型车',
    'truck': '货车',
    'bus': '客车'
  }
  return typeMap[type] || '未知'
}

// 获取结果样式类
const getResultClass = (result: string) => {
  if (result === '核验通过') return 'result-pass'
  if (result === '核验驳回') return 'result-reject'
  return 'result-pending'
}

// 预览照片
const previewPhoto = (index: number) => {
  const urls = vehicleDetail.photos.map(photo => photo.url)
  uni.previewImage({
    urls: urls,
    current: index
  })
}

// 核验通过/确认处理
const handleApprove = async () => {
  const isUnconfirmed = vehicleDetail.status === 'unconfirmed'
  const title = isUnconfirmed ? '确认处理' : '确认通过'
  const content = isUnconfirmed 
    ? `确定要处理车牌号为 ${vehicleDetail.plateNumber} 的未确认订单吗？` 
    : '确定该车辆核验通过吗？'
  
  uni.showModal({
    title,
    content,
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用API核验通过或确认处理
          // if (isUnconfirmed) {
          //   await confirmUnconfirmedOrder(vehicleId.value)
          // } else {
          //   await approveVehicle(vehicleId.value)
          // }
          
          uni.showToast({
            title: '操作成功',
            icon: 'success'
          })
          
          // 更新状态
          vehicleDetail.status = 'completed'
          vehicleDetail.result = isUnconfirmed ? '已确认处理' : '核验通过'
          vehicleDetail.verifyTime = new Date().toLocaleString()
          vehicleDetail.verifyPerson = '当前用户'
          
          // 添加历史记录
          vehicleDetail.historyRecords.unshift({
            time: new Date().toLocaleString(),
            action: isUnconfirmed ? '确认处理' : '核验通过',
            operator: '当前用户',
            remark: isUnconfirmed ? '确认处理未确认订单' : '现场核验通过'
          })
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
          
        } catch (error) {
          console.error(isUnconfirmed ? '确认处理失败:' : '核验通过失败:', error)
          uni.showToast({
            title: '操作失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

// 核验驳回/拒绝处理
const handleReject = () => {
  const isUnconfirmed = vehicleDetail.status === 'unconfirmed'
  showRejectModal.value = true
  rejectReason.value = ''
}

// 确认驳回/拒绝处理
const confirmReject = async () => {
  const isUnconfirmed = vehicleDetail.status === 'unconfirmed'
  const reasonTitle = isUnconfirmed ? '请输入拒绝处理原因' : '请输入驳回原因'
  
  if (!rejectReason.value.trim()) {
    uni.showToast({
      title: reasonTitle,
      icon: 'none'
    })
    return
  }
  
  try {
    // TODO: 调用API核验驳回或拒绝处理
    // if (isUnconfirmed) {
    //   await rejectUnconfirmedOrder(vehicleId.value, rejectReason.value)
    // } else {
    //   await rejectVehicle(vehicleId.value, rejectReason.value)
    // }
    
    uni.showToast({
      title: '操作成功',
      icon: 'success'
    })
    
    // 更新状态
    vehicleDetail.status = 'completed'
    vehicleDetail.result = isUnconfirmed ? '已拒绝处理' : '核验驳回'
    vehicleDetail.verifyTime = new Date().toLocaleString()
    vehicleDetail.verifyPerson = '当前用户'
    vehicleDetail.verifyRemark = rejectReason.value
    
    // 添加历史记录
    vehicleDetail.historyRecords.unshift({
      time: new Date().toLocaleString(),
      action: isUnconfirmed ? '拒绝处理' : '核验驳回',
      operator: '当前用户',
      remark: rejectReason.value
    })
    
    showRejectModal.value = false
    
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    
  } catch (error) {
    console.error(isUnconfirmed ? '拒绝处理失败:' : '核验驳回失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    })
  }
}

// 返回任务详情页面
const handleBackToDetail = () => {
  uni.redirectTo({
    url: `/pages/vehicle-internal-verify/detail?id=${taskId.value}`
  })
}
</script>

<style lang="scss" scoped>
.vehicle-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.detail-container {
  padding: 20rpx;
}

.info-card,
.verify-card,
.photo-card,
.history-card,
.action-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  padding: 30rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
  
  &.status-pending {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.status-completed {
    background-color: #f6ffed;
    color: #52c41a;
  }
  
  &.status-unconfirmed {
    background-color: #fff1f0;
    color: #ff4d4f;
  }
}

.card-content {
  padding: 20rpx 30rpx 30rpx;
}

.vehicle-plate-section {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.plate-number {
  font-size: 40rpx;
  font-weight: bold;
  color: #333333;
  margin-right: 20rpx;
}

.vehicle-type {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  background-color: #f0f0f0;
  color: #666666;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 8rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.verify-info {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.verify-item {
  display: flex;
  align-items: flex-start;
}

.verify-label {
  font-size: 28rpx;
  color: #666666;
  min-width: 160rpx;
}

.verify-value {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
  
  &.result-pass {
    color: #52c41a;
    font-weight: 600;
  }
  
  &.result-reject {
    color: #ff4d4f;
    font-weight: 600;
  }
  
  &.result-pending {
    color: #fa8c16;
    font-weight: 600;
  }
}

.no-verify {
  text-align: center;
  padding: 40rpx 0;
}

.no-verify-text {
  font-size: 28rpx;
  color: #999999;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.photo-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.photo-image {
  width: 100%;
  height: 160rpx;
  border-radius: 12rpx;
  background-color: #f5f5f5;
}

.photo-desc {
  font-size: 22rpx;
  color: #666666;
  margin-top: 8rpx;
  text-align: center;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.history-item {
  display: flex;
  gap: 20rpx;
}

.history-time {
  min-width: 280rpx;
}

.time-text {
  font-size: 24rpx;
  color: #999999;
}

.history-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.action-text {
  font-size: 28rpx;
  color: #333333;
  font-weight: 600;
}

.operator-text {
  font-size: 24rpx;
  color: #666666;
}

.remark-text {
  font-size: 26rpx;
  color: #999999;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  padding: 30rpx;
}

.reject-modal {
  background-color: #ffffff;
  border-radius: 20rpx;
  width: 600rpx;
  max-width: 90vw;
}

.modal-header {
  padding: 30rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  text-align: center;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.modal-content {
  padding: 30rpx;
}

.modal-footer {
  display: flex;
  padding: 20rpx 30rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
}
</style>